package com.dnake.service;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;


import com.dnake.Constant;
import com.dnake.entity.EventBusTimeBean;
import com.dnake.panel.MainActivity;
import com.dnake.utils.FileUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * 时间广播
 * 检测应用是否退出  退出就重启
 * 删除文件夹
 * 通过eventbus更新时间显示 在凌晨两点执行一些操作  检测第三方库情况
 */
public class TimeTickService extends Service {
    private long times = 0;
    public static Context mContext = null;

    public TimeTickService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext =this;
        IntentFilter filter=new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(receiver,filter);
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //每分钟检测
            if (action.equals(Intent.ACTION_TIME_TICK)) {
                times++;
                EventBus.getDefault().post(new EventBusTimeBean(""));
                if (!MainActivity.mOK){
                    Intent newIntent = new Intent(getApplicationContext(), MainActivity.class);
                    PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, newIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    //退出程序
                    AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, restartIntent); // 1秒钟后重启应用
                    System.exit(0);
                }else if (times%60==0){
                    //60分钟 删除一次
//                    AppUtils.detectNetwork(context);
                    FileUtils.deleteFolderFile(Constant.FILE_DIR, true);
                }
            }
        }
    };
}
